import { User } from "server/models/User";
import { FileModel } from "server/models/File";
import {
  successResponse,
  errorResponse,
  validationErrorResponse,
} from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const { id } = getRouterParams(event);
    const body = await readBody(event);
    const { username, email, nickname, avatar, bio, role, status } = body;

    if (!id) {
      return validationErrorResponse("用户ID不能为空");
    }

    // 验证字段
    if (username && (username.length < 3 || username.length > 20)) {
      return validationErrorResponse("用户名长度必须在3-20个字符之间");
    }

    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return validationErrorResponse("请输入有效的邮箱地址");
    }

    try {
      const userId = parseInt(id);
      
      // 处理头像字段：验证文件是否存在
      if (avatar !== null && avatar !== undefined) {
        if (typeof avatar === 'number') {
          // 验证文件是否存在
          const avatarFile = await FileModel.findById(avatar);
          if (!avatarFile) {
            return validationErrorResponse("头像文件不存在");
          }
        } else if (typeof avatar === 'string' && avatar !== '') {
          // 兼容旧的字符串URL格式，尝试转换为文件ID
          return validationErrorResponse("头像格式错误，请使用文件ID");
        }
      }

      const success = await User.updateProfile(userId, {
        username,
        email,
        nickname,
        avatar,
        bio,
        role,
        status,
      });

      if (!success) {
        return errorResponse("用户更新失败", "用户不存在");
      }

      return successResponse(null, "用户更新成功");
    } catch (dbError) {
      console.warn("数据库操作失败，使用模拟数据:", dbError);
    }
  } catch (error) {
    console.error("更新用户失败:", error);
    return errorResponse(
      "更新用户失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});
